package com.yssoft.service.inventory;

import com.yssoft.entity.inventory.TInstock;
import com.yssoft.entity.inventory.TInstockApply;
import com.yssoft.entity.inventory.TInstockApplyDetail;
import com.yssoft.entity.inventory.TInstockDetail;
import com.yssoft.entity.production.TLabels;
import com.yssoft.mapper.inventory.TInstockApplyDetailMapper;
import com.yssoft.mapper.inventory.TInstockApplyMapper;
import com.yssoft.mapper.inventory.TInstockDetailMapper;
import com.yssoft.mapper.inventory.TInstockMapper;
import com.yssoft.mapper.production.TLabelsMapper;
import com.yssoft.mapper.production.TWorksheetMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.ObjectConversion;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @创建人: 陈翼东
 * @时间: 2018/5/16 下午 08:06
 * @说明: 入库service
 */
@Service
public class InstockService {
    
    private static Logger logger = Logger.getLogger(InstockService.class);
    /**
     * 入库申请单
     */
    @Resource
    private TInstockApplyMapper instockApplyMapper;
    
    @Resource
    private TInstockApplyDetailMapper instockApplyDetailMapper;
    
    @Resource
    private TInstockMapper instockMapper;
    
    @Resource
    private TInstockDetailMapper instockDetailMapper;
    
    @Resource
    private TWorksheetMapper worksheetMapper;
    
    @Resource
    private TLabelsMapper labelsMapper;
    
    /**
     * @方法名: getWarehousingApplyMatrial
     * @创建人: 陈翼东
     * @时间: 2018/5/17 上午 10:16
     * @参数: [page, pageSize, materialType, applyDate]
     * @返回值: java.util.List<java.util.Map   <   java.lang.String   ,   java.lang.Object>>
     * @说明: 查询已经审核通过的入库申请单
     */
    public List<Map<String, Object>> getWarehousingApply(int page, int pageSize, String materialType, String applyDate, HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            int start = ((page - 1) * pageSize);
            params.put("page", start);
            params.put("pageSize", pageSize);
            params.put("materialType", materialType == null ? null : (materialType.length() <= 0 ? null : materialType));
            params.put("applyDate", applyDate == null ? null : (applyDate.length() <= 0 ? null : applyDate));
            params.put("entid", AppUserHelper.getCurrentCompanyId(request));
            List<Map<String, Object>> instockApplyList = instockApplyMapper.selectInstockApplyByMaterType(params);
            for (Map<String, Object> instockApply : instockApplyList) {
                List<Map<String, Object>> instockApplyDetailList = instockApplyDetailMapper.selectInstockApplyDetailByInfo(instockApply.get("id") + "");
                instockApply.put("instockApplyDetailList", instockApplyDetailList);
            }
            return instockApplyList;
        } catch (Exception e) {
            logger.error("查询入库申请单失败!");
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     *
     * @方法名: getWarehousingApplyMatrial
     * @创建人: 陈翼东
     * @时间: 2018/5/17 上午 10:16
     * @参数: [page, pageSize, materialType, applyDate]
     * @返回值: java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
     * @说明: 查询入库申请单和入库申请单明细
     */
    public List<Map<String, Object>> getWarehousingList(int page, int pageSize, String materialType, String applyDate, HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            int start = ((page - 1) * pageSize);
            params.put("page", start);
            params.put("pageSize", pageSize);
            params.put("materialType", materialType == null ? null : (materialType.length() <= 0 ? null : materialType));
            params.put("applyDate", applyDate == null ? null : (applyDate.length() <= 0 ? null : applyDate));
            params.put("entid", AppUserHelper.getCurrentCompanyId(request));
            List<Map<String, Object>> instockList = instockMapper.selectInstockByMaterType(params);
            for (Map<String, Object> instock : instockList) {
                List<Map<String, Object>> instockDetailList = instockDetailMapper.selectInstockDetailByInfo(instock.get("id") + "");
                instock.put("instockDetailList", instockDetailList);
            }
            return instockList;
        } catch (Exception e) {
            logger.error("查询入库单失败!");
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * @方法名: getWarehousingApplyDetail
     * @创建人: 陈翼东
     * @时间: 2018/5/17 下午 01:39
     * @参数: [warehousingApplicationId]
     * @返回值: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @说明: 通过入库申请单查询申请单明细
     */
    public Map<String, Object> getWarehousingApplyDetail(String warehousingApplicationId, String warehousingApplicationDetailId) {
        try {
            TInstockApply instockApply = instockApplyMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationId));
            Map<String, Object> instockApplyMap = ObjectConversion.getObjectToMap(instockApply);
            //查询出订单所有详情
            //List<Map<String, Object>>  instockApplyDetailList=instockApplyDetailMapper.selectInstockApplyDetailByInfo (warehousingApplicationId);
            //单个详情入库
            List<Map<String, Object>> instockApplyDetailList = instockDetailMapper.selectInstockApplyDetailByDetailId(warehousingApplicationDetailId);
            instockApplyMap.put("instockApplyDetailList", instockApplyDetailList);
            return instockApplyMap;
        } catch (Exception e) {
            logger.error("通过入库申请单查询申请单明细失败!");
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * @方法名: saveWarehousingMaterial
     * @创建人: 陈翼东
     * @时间: 2018/5/17 下午 01:45
     * @参数: [warehousingApplicationId, warehousingNumber]入库申请单id,入库数量
     * @返回值: void
     * @说明: 保存物料，添加剂,辅料,包材的入库信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Object saveWarehousingMaterial(String warehousingApplicationId, String[] warehousingApplicationDetailId, String[] warehousingDetailNumber, HttpServletRequest request) {
        //通过申请单id查询出申请单
        //通过申请单生成入库单
        //通过申请明细生成入库明细
        //入库单和入库申请单关系，及入库明细单和入库申请明细单，入库单和入库明细的关系
        try {
            TInstockApply instockApply = instockApplyMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationId));//入库申请
            //-----生成入库单----默认直接是入库状态------
            TInstock instock = new TInstock();//入库单
            instock.setCode("RK" + System.currentTimeMillis());
            instock.setDeptId(AppUserHelper.getCurrentDeptId(request));
            instock.setDeptName(AppUserHelper.getCurrentDeptName(request));
            BigDecimal zongshu = new BigDecimal(0);
            if (warehousingDetailNumber == null) {
                return AppUtil.returnMapJson("0", "请传递入库数量!", null);
            }
            for (String number : warehousingDetailNumber) {
                zongshu = zongshu.add(new BigDecimal(number));
            }
            instock.setQuantity(zongshu);//入库数量
            instock.setStat("2");
            instock.settEId(AppUserHelper.getCurrentCompanyId(request));
            instock.setCreateTime(new Date());
            instock.setCreatorId(AppUserHelper.getCurrentUserId(request));
            instock.setCreatorName(AppUserHelper.getCurrentUserName(request));
            instock.setDeleteFlag("0");
            instock.settWarehouseId(instockApply.gettWarehouseId());
            instockMapper.insert(instock);
            //---------------将入库申请单变成已入库----------------
            instockApply.setStat("2");
            instockApply.settInstockId(instock.getId());//入库申请单和入库单关系
            instockApplyMapper.updateByPrimaryKeySelective(instockApply);
            //----查询入库申请明细，生成入库明细--------
            for (int i = 0; i < warehousingApplicationDetailId.length; i++) {//后台多个申请详情单分别生成入库详情单
                TInstockApplyDetail instockApplyDetail = instockApplyDetailMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationDetailId[i]));
                TInstockDetail instockDetail = new TInstockDetail();
                instockDetail.setDeptId(AppUserHelper.getCurrentDeptId(request));
                instockDetail.setDeptName(AppUserHelper.getCurrentDeptName(request));
                instockDetail.settEId(AppUserHelper.getCurrentCompanyId(request));
                instockDetail.setCreatorId(AppUserHelper.getCurrentUserId(request));
                instockDetail.setCreatorName(AppUserHelper.getCurrentUserName(request));
                instockDetail.setCreateTime(new Date());
                instockDetail.setQuantity(new BigDecimal(warehousingDetailNumber[i]));//入库数量
                instockDetail.setMargin(new BigDecimal(warehousingDetailNumber[i]));//库存余量默认是入库数量
                instockDetail.setpType(instockApplyDetail.getpType());
                instockDetail.settInAppDId(instockApplyDetail.getId());//入库明细和入库申请明细关系
                instockDetail.settInstockId(instock.getId());//入库明细和入库单关系
                instockDetail.settMId(instockApplyDetail.gettMId());
                instockDetail.settPId(instockApplyDetail.gettPId());
                instockDetail.settSgId(instockApplyDetail.gettSgId());
                instockDetail.settWarehouseId(instockApplyDetail.gettWarehouseId());
                instockDetail.setDeleteFlag("0");
                instockDetail.settWarehouseId(instockApplyDetail.gettWarehouseId());
                instockDetailMapper.insert(instockDetail);
                instockApplyDetail.setStat("2");//将入库申请详情状态变成已经入库
                instockApplyDetailMapper.updateByPrimaryKeySelective(instockApplyDetail);
            }
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存入库单失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }
    
    /**
     * @方法名: getApplyDetailByBatch
     * @创建人: 陈翼东
     * @时间: 2018/5/18 下午 04:18
     * @参数: [code]
     * @返回值: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @说明: 根据标签获取加工单id
     */
    public Map<String, Object> getApplyDetailByBatch(String code) {
        return worksheetMapper.getApplyDetailByBatch(code);
    }
    
    /**
     * @方法名: getWorksheetByApplyDetail
     * @创建人: 陈翼东
     * @时间: 2018/5/18 下午 04:43
     * @参数: [applyDetailId]
     * @返回值: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @说明: 根据入库申请明细查询加工单id
     */
    public Map<String, Object> getWorksheetByApplyDetail(String applyDetailId) {
        return worksheetMapper.selectByApplyDetail(applyDetailId);
    }
    
    /**
     * @方法名: getWorksheetAndPeatchByBeatch
     * @创建人: 陈翼东
     * @时间: 2018/5/18 下午 07:22
     * @参数: [worksheetid]
     * @返回值: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @说明: 根据加工单id获取加工单信息和批次信息
     */
    public Map<String, Object> getWorksheetAndPeatchByBeatch(String worksheetid) {
        return worksheetMapper.selectWorksheetAndBeatch(worksheetid);
        
    }
    
    
    /**
     * @方法名: saveWarehousingMaterial
     * @创建人: 陈翼东
     * @时间: 2018/5/17 下午 01:45
     * @参数: [warehousingApplicationId, warehousingNumber]入库申请单id,入库数量
     * @返回值: void
     * @说明: 保存物料，添加剂,辅料,包材的入库信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Object saveWarehousingBatch(String warehousingApplicationId, String[] warehousingApplicationDetailId, String[] warehousingDetailNumber, String[] labelId, HttpServletRequest request) {
        //通过申请单id查询出申请单
        //通过申请单生成入库单
        //通过申请明细生成入库明细
        //入库单和入库申请单关系，及入库明细单和入库申请明细单，入库单和入库明细的关系
        try {
            TInstockApply instockApply = instockApplyMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationId));//入库申请
            //-----生成入库单----默认直接是入库状态------
            TInstock instock = new TInstock();//入库单
            instock.setCode("RK" + System.currentTimeMillis());
            instock.setDeptId(AppUserHelper.getCurrentDeptId(request));
            instock.setDeptName(AppUserHelper.getCurrentDeptName(request));
            BigDecimal zongshu = new BigDecimal(0);
            if (warehousingDetailNumber == null) {
                return AppUtil.returnMapJson("0", "请传递入库数量!", null);
            }
            for (String number : warehousingDetailNumber) {
                zongshu = zongshu.add(new BigDecimal(number));
            }
            instock.setQuantity(zongshu);//入库数量
            instock.setStat("2");
            instock.settEId(AppUserHelper.getCurrentCompanyId(request));
            instock.setCreateTime(new Date());
            instock.setCreatorId(AppUserHelper.getCurrentUserId(request));
            instock.setCreatorName(AppUserHelper.getCurrentUserName(request));
            instock.setDeleteFlag("0");
            instock.settWarehouseId(instockApply.gettWarehouseId());
            instockMapper.insert(instock);
            //---------------将入库申请单变成已入库----------------
            instockApply.setStat("2");
            instockApply.settInstockId(instock.getId());//入库申请单和入库单关系
            instockApplyMapper.updateByPrimaryKeySelective(instockApply);
            //----查询入库申请明细，生成入库明细--------
            for (int i = 0; i < warehousingApplicationDetailId.length; i++) {//后台多个申请详情单分别生成入库详情单
                TInstockApplyDetail instockApplyDetail = instockApplyDetailMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationDetailId[i]));
                TInstockDetail instockDetail = new TInstockDetail();
                instockDetail.setDeptId(AppUserHelper.getCurrentDeptId(request));
                instockDetail.setDeptName(AppUserHelper.getCurrentDeptName(request));
                instockDetail.settEId(AppUserHelper.getCurrentCompanyId(request));
                instockDetail.setCreatorId(AppUserHelper.getCurrentUserId(request));
                instockDetail.setCreatorName(AppUserHelper.getCurrentUserName(request));
                instockDetail.setCreateTime(new Date());
                instockDetail.setQuantity(new BigDecimal(warehousingDetailNumber[i]));//入库数量
                instockDetail.setMargin(new BigDecimal(warehousingDetailNumber[i]));//库存余量默认是入库数量
                instockDetail.setpType(instockApplyDetail.getpType());
                instockDetail.settInAppDId(instockApplyDetail.getId());//入库明细和入库申请明细关系
                instockDetail.settInstockId(instock.getId());//入库明细和入库单关系
                instockDetail.settMId(instockApplyDetail.gettMId());
                instockDetail.settPId(instockApplyDetail.gettPId());
                instockDetail.settSgId(instockApplyDetail.gettSgId());
                instockDetail.settWarehouseId(instockApplyDetail.gettWarehouseId());
                instockDetail.setDeleteFlag("0");
                instockDetail.settWarehouseId(instockApplyDetail.gettWarehouseId());
                instockDetailMapper.insert(instockDetail);
                instockApplyDetail.setStat("2");//将入库申请详情状态变成已经入库
                instockApplyDetailMapper.updateByPrimaryKeySelective(instockApplyDetail);
                //根据入库申请单查询出标签
                TLabels label = labelsMapper.selectByPrimaryKey(Integer.parseInt(labelId[i]));
                label.settInstockDId(instockDetail.getId());//保存标签和入库单关系
                labelsMapper.updateByPrimaryKeySelective(label);
            }
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存入库单失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }
    
    /**
     * @方法名: getLabelByCode
     * @创建人: 陈翼东
     * @时间: 2018/5/18 下午 08:17
     * @参数: [code]
     * @返回值: java.lang.Object
     * @说明: 根据标签码获取标签
     */
    public TLabels getLabelByCode(String code) {
        return labelsMapper.selectByCode(code);
    }
    
    /**
     * @方法名: getWorksheetByLabelPackage
     * @创建人: 陈翼东
     * @时间: 2018/5/19 上午 09:23
     * @参数: [code]
     * @返回值: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @说明: 根据标签获取包装码获取加工单
     */
    public Map<String, Object> getWorksheetByLabelPackage(String codeId) {
        return worksheetMapper.selectByPackageCodeId(codeId);
    }
    
    /**
     * @方法名: getWorksheetByPackageCode
     * @创建人: 陈翼东
     * @时间: 2018/5/19 上午 09:58
     * @参数: [packageCode]
     * @返回值: java.lang.Object
     * @说明: 根据包装码获取加工单信息
     */
    public Map<String, Object> getWorksheetByPackageCode(String packageCode) {
        return worksheetMapper.selectIdByPackageCode(packageCode);
    }
    
    /**
     * @方法名: getLablesByPackageCode
     * @创建人: 陈翼东
     * @时间: 2018/5/19 上午 09:58
     * @参数: [packageCode]
     * @返回值: java.lang.Object
     * @说明: 根据包装码获取标签信息
     */
    public List<Map<String, Object>> getLablesByPackageCode(String packageCode) {
        return labelsMapper.selectByPackageCode(packageCode);
    }
    
    /**
     * @方法名: saveWarehousingUnit
     * @创建人: 陈翼东
     * @时间: 2018/5/19 下午 01:18
     * @参数: [warehousingApplicationId, warehousingApplicationDetailId, warehousingDetailNumber, labelId, request]
     * @返回值: java.lang.Object
     * @说明: 个体入库保存
     */
    @Transactional(rollbackFor = Exception.class)
    public Object saveWarehousingUnit(String warehousingApplicationId, String warehousingApplicationDetailId, String[] labelId, HttpServletRequest request) {
        //通过申请单id查询出申请单
        //通过申请单生成入库单
        //通过申请明细生成入库明细
        //入库单和入库申请单关系，及入库明细单和入库申请明细单，入库单和入库明细的关系
        try {
            TInstockApply instockApply = instockApplyMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationId));//入库申请
            //-----生成入库单----默认直接是入库状态------
            TInstock instock = new TInstock();//入库单
            instock.setCode("RK" + System.currentTimeMillis());
            instock.setDeptId(AppUserHelper.getCurrentDeptId(request));
            instock.setDeptName(AppUserHelper.getCurrentDeptName(request));
            BigDecimal zongshu = new BigDecimal(0);
            instock.setQuantity(new BigDecimal(labelId.length));//入库数量
            instock.setStat("2");
            instock.settEId(AppUserHelper.getCurrentCompanyId(request));
            instock.setCreateTime(new Date());
            instock.setCreatorId(AppUserHelper.getCurrentUserId(request));
            instock.setCreatorName(AppUserHelper.getCurrentUserName(request));
            instock.setDeleteFlag("0");
            instock.settWarehouseId(instockApply.gettWarehouseId());
            instockMapper.insert(instock);
            //---------------将入库申请单变成已入库----------------
            instockApply.setStat("2");
            instockApply.settInstockId(instock.getId());//入库申请单和入库单关系
            instockApplyMapper.updateByPrimaryKeySelective(instockApply);
            //----查询入库申请明细，生成入库明细--------
            TInstockApplyDetail instockApplyDetail = instockApplyDetailMapper.selectByPrimaryKey(Integer.parseInt(warehousingApplicationDetailId));
            TInstockDetail instockDetail = new TInstockDetail();
            instockDetail.setDeptId(AppUserHelper.getCurrentDeptId(request));
            instockDetail.setDeptName(AppUserHelper.getCurrentDeptName(request));
            instockDetail.settEId(AppUserHelper.getCurrentCompanyId(request));
            instockDetail.setCreatorId(AppUserHelper.getCurrentUserId(request));
            instockDetail.setCreatorName(AppUserHelper.getCurrentUserName(request));
            instockDetail.setCreateTime(new Date());
            instockDetail.setQuantity(new BigDecimal(labelId.length));//入库数量
            instockDetail.setMargin(new BigDecimal(labelId.length));//库存余量默认是入库数量
            instockDetail.setpType(instockApplyDetail.getpType());
            instockDetail.settInAppDId(instockApplyDetail.getId());//入库明细和入库申请明细关系
            instockDetail.settInstockId(instock.getId());//入库明细和入库单关系
            instockDetail.settMId(instockApplyDetail.gettMId());
            instockDetail.settPId(instockApplyDetail.gettPId());
            instockDetail.settSgId(instockApplyDetail.gettSgId());
            instockDetail.settWarehouseId(instockApplyDetail.gettWarehouseId());
            instockDetail.setDeleteFlag("0");
            instockDetail.settWarehouseId(instockApplyDetail.gettWarehouseId());
            instockDetailMapper.insert(instockDetail);
            instockApplyDetail.setStat("2");//将入库申请详情状态变成已经入库
            instockApplyDetailMapper.updateByPrimaryKeySelective(instockApplyDetail);
            //根据入库申请单查询出标签
            for (String id: labelId) {
                TLabels label = labelsMapper.selectByPrimaryKey(Integer.parseInt(id));
                label.settInstockDId(instockDetail.getId());//保存标签和入库单关系
                labelsMapper.updateByPrimaryKeySelective(label);
            }
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存入库单失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }
}
